<template>
  <div v-show="fields.length">
    <div v-for="(item, index) in list" :key="index">
      <batch-form
        :fields="fields"
        :column-num="columnNum"
        :list="list"
        :index="index"
        :type="type"
        ref="batchForm"
        @add="add"
        @del="del"
        :item="item"
      />
    </div>
  </div>
</template>

<script>
/* utils */
import _ from 'lodash';
import { isEmpty } from '@src/util/type'
import { matchOperator, setFieldOperateHandler, DateFormType } from './common.js';
import BatchForm from './BatchForm.vue';

export default {
  name: 'inquire',
  props: {
    taskNums: {
      type: Array || null,
      default: () => [], // 已经存储的视图参数索引
    },
    config: {
      type: Array,
      default: () => ({}),
    },
    columnNum: {
      type: Number,
      default: 1,
    },
    type: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      list: [1],
    };
  },
  watch: {
    taskNums: {
      handler(val) {
        this.list = val;
      },
      immediate: true,
    },
    config() {
      this.fields;
    },
  },
  computed: {
    // 处理一下fields
    fields() {
      let f = {};
      let fields = [...this.config].map(field => {
        f = _.cloneDeep(field);
        let formType = f.formType;

        if (DateFormType.includes(formType)) {
          formType = 'date';
        }

        if (formType === 'updateTime') {
          f.displayName = '更新时间';
        }

        // 设置 字段 条件选项
        setFieldOperateHandler(f);

        return {
          ...f,
          isNull: 1,
          formType,
          originalFormType: f.formType,
          operator: matchOperator(f),
        };
      });
      return fields;
    },
  },
  methods: {
    // 返回表单数据
    returnData() {
      let data = {};
      if (!this.$refs.batchForm) return {};
      this.$refs.batchForm.forEach(item => {
        for (let key in item.returnData()) {
          const value = item.returnData()[key];
          // if (value && !isEmpty(value)) {
          //   data[key] = item.returnData()[key];
          // }
          data[key] = value;
        }
      });
      return data;
    },

    // 返回表单字段
    returnInquireFields() {
      if (!this.$refs.batchForm) return [];

      let inquireFields = [];
      this.$refs.batchForm.forEach(batchFormEl => {
        inquireFields.push(batchFormEl.selectedField);
      });

      return inquireFields;
    },

    // 添加
    add() {
      this.list.push(1);
    },

    // 删除
    del({ index, value }) {
      this.list = this.list.map((item, i) => {
        if (index === i) {
          item = '';
        }
        return item;
      });
    },
  },
  components: {
    BatchForm,
  },
};
</script>
